package com.example.common.mvvm

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import com.example.common.base.BaseFragment
import com.example.common.event.BaseEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMvvmFragment <T: ViewDataBinding>:BaseFragment<T>() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = super.onCreateView(inflater, container, savedInstanceState)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setDataObserver()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event :BaseEvent){
        if (event!=null &&event.target== this::class.java.simpleName){
            sendEvent(event)
        }
    }

    open fun sendEvent(event :BaseEvent){


    }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }


    open fun lazyLoadData(){

    }

    open fun setDataObserver(){

    }


}